const user = require("../../database/user");

module.exports = async (req, res, next)=>{
  // 接收并解析前端请求时携带的数据
  const {userId, nickname, name, tel, age, sex, power, job, teamId} = req.body;

  // 密码单独修改
  // 头像单独修改
  
  // 判断是否传入必传参数
  if(!userId){
    res.send({
      code:2,
      msg:"缺少必传参数：userId"
    })
    return;
  }

  // 将可能被修改的数据，打包
  const newData = {};
  if( nickname ) newData.nickname = nickname;
  if( name ) newData.name = name;
  if( tel ) newData.tel = tel;
  if( age ) newData.age = age-0;
  if( sex ) newData.sex = sex;
  if( power ) newData.power = power;
  if( job ) newData.job = job;
  if( teamId ) newData.teamId = teamId;
  
  // const {userId} = req.body;
  // for(let i in req.body){
  //   if(req.body[i] !== undefined && req.body[i] !== "" && i !== "userId"){
  //     newData[i] = req.body[i]
  //   }
  // }

  try {
    // 开始修改：userId为条件，打包后的数据为要修改的数据
    await user.updateOne({userId}, newData);
    // 如果修改的信息中，存在职位修改，将来还需要不同修改部门信息
    // await team.updateOne({teamId}, {teamLeader:userId})
    res.send({
      code:1,
      msg:"修改成功"
    })
  } catch (error) {
    res.send({
      code:0,
      msg:"修改失败"
    })
  }
}